﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Ortodoctor.modelo;
using Ortodoctor.gridComponent;
using System.Web.Services;

namespace Ortodoctor.Funcionario
{
    public partial class Orcamento : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USUARIO"] == null)
                Response.Redirect("Login.aspx");


            modeloOrcamento model = new modeloOrcamento();
            Grid grid = new Grid(model.getAll(), "id_orcamento");
            Session["GRID_ORCAMENTO"] = grid;

            usuario.InnerText = Session["USUARIO"].ToString().ToUpper();
            modeloCliente modelo = new modeloCliente();
            DataTable dt = modelo.getAll();
            dt.DefaultView.Sort = "[nome] ASC";
            dt = dt.DefaultView.ToTable();
            string options = "";
            foreach (DataRow dr in dt.Rows)
            {
                options += string.Format("<option value='{0}' >{1}</option>", dr["id_cliente"].ToString(), dr["nome"].ToString());
            }
            options = "<select id='selectID' style='width: 100%'>" + options + "</select>";
            string selectClient = "$('#selectID').replaceWith($(\"" + options + "\"));";


            modeloProcedimento modeloproc = new modeloProcedimento();
            dt = modeloproc.getAll();
            dt.DefaultView.Sort = "[nome_procedimento] ASC";
            dt = dt.DefaultView.ToTable();
            string procedimento = "";
            foreach (DataRow dr in dt.Rows)
            {
                procedimento += string.Format("<option value='{0}' >{1}</option>", dr["id_procedimento"].ToString(), dr["nome_procedimento"].ToString());
            }
            procedimento = "<select id='procedimento' style='width: 100%'>" + procedimento + "</select>";
            string selectProc = "$('#procedimento').replaceWith($(\"" + procedimento + "\"));";

            scripts.InnerHtml = "<script> " + selectClient + selectProc + "</script>";
        }

        [WebMethod]
        public static string getDados(string page, string rp, string sortname, string sortorder, string query, string qtype)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_ORCAMENTO"]);
            grid.page = Convert.ToInt32(page);
            DataTable dt = grid.dados.Clone();

            if (string.IsNullOrEmpty(query))
            {
                int numeroItensPagina = Convert.ToInt32(rp);
                int numeroPagina = Convert.ToInt32(page);
                int inicio = numeroItensPagina * (numeroPagina - 1);

                for (int i = inicio; i < inicio + numeroItensPagina && i < grid.dados.Rows.Count; ++i)
                {
                    DataRow dr = dt.NewRow();
                    foreach (DataColumn dc in dt.Columns)
                        dr[dc.ColumnName] = grid.dados.Rows[i][dc.ColumnName];

                    dt.Rows.Add(dr);
                }
                if (dt.Rows.Count > 0)
                {
                    dt.DefaultView.Sort = sortname + " " + sortorder;
                    dt = dt.DefaultView.ToTable();
                }
            }
            else
            {
                dt = grid.dados.Copy();
                dt.DefaultView.RowFilter = string.Format("[{0}] like '%{1}%'", qtype, query);
                dt = dt.DefaultView.ToTable();
            }
            return grid.getDadosToJson(dt);
        }

        [WebMethod]
        public static string addToTable(string dados)
        {
            string[] array = dados.Split('|');
            modeloOrcamento model = new modeloOrcamento();
            int p0 = 0; int p1 = 0; int p2 = 0; int p3 = 0; int p4 = 0; int p5 = 0;
            try{ p0 = Convert.ToInt32(array[0]);} catch (Exception e) { p0 = -1; }
            try { p1 = Convert.ToInt32(HttpContext.Current.Session["ID_USUARIO_ACESSO"]); } catch (Exception e) { p1 = -1; }
            try { p2 = Convert.ToInt32(array[2].ToString()); } catch (Exception e) { p2 = -1; }
            try { p3 = Convert.ToInt32(array[4].ToString()); } catch (Exception e) { p3 = -1; }
            try { p4 = Convert.ToInt32(array[3].ToString()); } catch (Exception e) { p4 = -1; }
            try { p5 = Convert.ToInt32(array[1].ToString()); } catch (Exception e) { p5 = -1; }

            if ((p0 != -1) && (p1 != -1) && (p2 != -1) && (p3 != -1) && (p4 != -1))
            {
                Componentes.Orcamento orc = new Componentes.Orcamento(-1, p0, p1, p2, p3, p4, p5);
                int id = model.insert(orc);
                orc.IdProcedimento = id;
                Grid grid = ((Grid)HttpContext.Current.Session["GRID_ORCAMENTO"]);

                DataTable retorno = model.getOrcamento(id);
                DataRow dr = grid.dados.NewRow();
                try
                {
                    dr["id_orcamento"] = retorno.Rows[0]["id_orcamento"];
                    dr["nome"] = retorno.Rows[0]["nome"];
                    dr["login"] = retorno.Rows[0]["login"];
                    dr["nome_procedimento"] = retorno.Rows[0]["nome_procedimento"];
                    dr["tempo_tratamento"] = retorno.Rows[0]["tempo_tratamento"];
                    dr["valor_parcela"] = retorno.Rows[0]["valor_parcela"];
                    dr["valor_total"] = retorno.Rows[0]["valor_total"];
                    grid.total++;
                    grid.dados.Rows.Add(dr);

                    HttpContext.Current.Session["GRID_ORCAMENTO"] = grid;
                    return "adicionou";
                }
                catch (Exception e) { return "Falha"; }
            }
            else return "Falha";
        }

        [WebMethod]
        public static string editTable(int id, string dados)
        {
            string[] array = dados.Split('|');
            modeloOrcamento model = new modeloOrcamento();
            int p0 = 0; int p1 = 0; int p2 = 0; int p3 = 0; int p4 = 0; int p5 = 0;
            try { p0 = Convert.ToInt32(array[0]); }
            catch (Exception e) { p0 = 0; }
            try { p1 = Convert.ToInt32(HttpContext.Current.Session["ID_USUARIO_ACESSO"]); }
            catch (Exception e) { p1 = 0; }
            try { p2 = Convert.ToInt32(array[2].ToString()); }
            catch (Exception e) { p2 = 0; }
            try { p3 = Convert.ToInt32(array[4].ToString()); }
            catch (Exception e) { p3 = 0; }
            try { p4 = Convert.ToInt32(array[3].ToString()); }
            catch (Exception e) { p4 = 0; }
            try { p5 = Convert.ToInt32(array[1].ToString()); }
            catch (Exception e) { p5 = 0; }
            Componentes.Orcamento orc = new Componentes.Orcamento(id, p0, p1, p2, p3, p4, p5);
            model.update(orc);
            orc.IdProcedimento = id;
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_ORCAMENTO"]);

            DataTable retorno = model.getOrcamento(id);
            DataRow dr = grid.dados.Select("[id_orcamento]=" + id)[0];
            dr["id_orcamento"] = retorno.Rows[0]["id_orcamento"];
            dr["nome"] = retorno.Rows[0]["nome"];
            dr["login"] = retorno.Rows[0]["login"];
            dr["nome_procedimento"] = retorno.Rows[0]["nome_procedimento"];
            dr["tempo_tratamento"] = retorno.Rows[0]["tempo_tratamento"];
            dr["valor_parcela"] = retorno.Rows[0]["valor_parcela"];
            dr["valor_total"] = retorno.Rows[0]["valor_total"];

            HttpContext.Current.Session["GRID_ORCAMENTO"] = grid;
            return "editou";
        }

        [WebMethod]
        public static string deleteFromTable(int id)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_ORCAMENTO"]);
            grid.deleteFromTable(id);
            modeloOrcamento orcamento = new modeloOrcamento();
            orcamento.delete(id);
            HttpContext.Current.Session["GRID_ORCAMENTO"] = grid;
            return "removeu";
        }

        [WebMethod]
        public static string getDataFromOrc(int id)
        {
            modeloOrcamento model = new modeloOrcamento();
            DataTable retorno = model.getOrcamento(id);
            string str = "";
            str += retorno.Rows[0]["id_orcamento"] + "|";
            str += retorno.Rows[0]["nome"] + "|";
            str += retorno.Rows[0]["login"] + "|";
            str += retorno.Rows[0]["nome_procedimento"] + "|";
            str += retorno.Rows[0]["tempo_tratamento"] + "|";
            str += retorno.Rows[0]["valor_parcela"] + "|";
            str += retorno.Rows[0]["valor_total"];

            return str;
        }
    }
}